/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sisfo.astacala.util;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author arif
 */
public class UtilFormExporter implements Runnable {

    private String fileName;
    private String exportType;
    private List<String> columnName;
    private List<Map> data;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getExportType() {
        return exportType;
    }

    public void setExportType(String exportType) {
        this.exportType = exportType;
    }

    public List<Map> getData() {
        return data;
    }

    public void setData(List<Map> data) {
        this.data = data;
    }

    public List<String> getColumnName() {
        return columnName;
    }

    public void setColumnName(List<String> columnName) {
        this.columnName = columnName;
    }

    public void exportToCSV() {
        try {
            Writer writer = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);

            StringBuilder header = new StringBuilder();
            for (int i = 0; i < columnName.size(); i++) {
                header.append(columnName.get(i));
                if ((i + 1) != columnName.size()) {
                    header.append(",");
                }
            }
            bufferedWriter.write(header.toString());
            bufferedWriter.newLine();

            for (int i = 0; i < data.size(); i++) {
                StringBuilder row = new StringBuilder();
                for (int j = 0; j < columnName.size(); j++) {
                    String colName = columnName.get(j).toLowerCase();
                    row.append(data.get(i).get(colName));
                    if ((i + 1) != columnName.size()) {
                        row.append(",");
                    }
                }
                bufferedWriter.write(row.toString());
                bufferedWriter.newLine();
            }
            bufferedWriter.close();
            writer.close();
        } catch (Exception ex) {
            Logger.getLogger(UtilFormExporter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void exportToExcel() {
        System.out.println("export to excel");
    }

    @Override
    public void run() {
        if (exportType.equals("csv")) {
            exportToCSV();
        } else if (exportType.equals("xls")) {
            exportToExcel();
        }
    }
}
